# @file    : baidu_trans_text
# @time    : 2025/4/17
# @author  : yongpeng.yao
# @desc    :
import hashlib
import uuid

import requests

from translate_excel_test.contains_lang import contains_japanese, contains_chinese, contains_english

APP_ID = '20221122001464331'
SECRET_KEY = 'SerbodwPCAiL2Zwm0PZv'


def baidu_translate_text(text, from_lang='jp', to_lang='zh'):
    """
    支持 jp（日语） zh（中文） en (英语)
    :param text:
    :param from_lang:
    :param to_lang:
    :return:
    """
    # 翻以前判断 如果text中不包含from_lang 则返回text
    if not text:
        return text
    if from_lang == 'ja' and not contains_japanese(text):
        return text
    if from_lang == 'zh' and not contains_chinese(text):
        return text
    if from_lang == 'en' and not contains_english(text):
        return text

    url = 'https://fanyi-api.baidu.com/api/trans/vip/translate'
    salt = str(uuid.uuid4())
    sign = hashlib.md5((APP_ID + text + salt + SECRET_KEY).encode()).hexdigest()

    params = {
        'q': text,
        'from': from_lang,
        'to': to_lang,
        'appid': APP_ID,
        'salt': salt,
        'sign': sign
    }

    response = requests.get(url, params=params)
    if response.status_code != 200:
        print(f"Error: {response.status_code}, result {response.text}")
    trans_result = response.json()['trans_result']
    result = '\n'.join([item['dst'] for item in trans_result])
    return result


if __name__ == '__main__':
    tran_text = baidu_translate_text('おはようございます。', 'jp', 'zh')
    print(tran_text)
